package com.xiongwei.manageback.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiongwei.manageback.domain.SysFile;
import com.xiongwei.manageback.exception.ServiceException;
import com.xiongwei.manageback.service.SysFileService;
import com.xiongwei.manageback.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件上传相关接口
 */
@RestController
@RequestMapping("/file")
@Api(tags = "文件上传相关接口")
public class FileController {

//    文件上传路径
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Autowired
    private SysFileService fileService;

    @ApiOperation("启用禁用文件")
    @PutMapping("/enableFile/{id}/{enable}")
    public AjaxResult enableFile(@PathVariable Integer id, @PathVariable Boolean enable) {
        int i = 0;
        return fileService.enable(enable, id);
    }

    @ApiOperation("批量删除文件")
    @PostMapping("/delete/batch")
    public boolean batchDeleteFile(@RequestBody List<Integer> ids) {
        return fileService.removeByIds(ids);
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/delete/{id}")
    public boolean deleteFile(@PathVariable("id") Integer id) {
        return fileService.removeById(id);
    }

    @ApiOperation("文件表分页查询")
    @GetMapping("/list")
    public Page pageQuery(@ApiParam("当前页数") @RequestParam() Integer pageNum,
                          @ApiParam("当前页返回结果数量") @RequestParam() Integer pageSize,
                          @ApiParam("文件名") @RequestParam(required = false, defaultValue = "") String name) {
        Page<SysFile> files = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysFile> wrapper = new LambdaQueryWrapper<SysFile>()
                .like(SysFile::getName, name);
        Page<SysFile> filePage = fileService.page(files, wrapper);
        return filePage;
    }


    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
//        根据原始文件名查询数据库，若存在，则返回已有的图片url
        LambdaQueryWrapper<SysFile> wrapper = new LambdaQueryWrapper<SysFile>().eq(SysFile::getName, fileName);
        List<SysFile> files = fileService.list(wrapper);
        if (files.size() > 0){
            return files.get(0).getUrl();
        }
//        文件类型，后缀
        String type = FileUtil.extName(fileName);
        long size = file.getSize();
        File directory = new File(fileUploadPath);
        if (!directory.exists()){
//            路径不存在，创建路径
            directory.mkdirs();
        }
//        文件唯一标识--文件名
        String uuid = IdUtil.fastSimpleUUID();
        String newFileName = uuid + StrUtil.DOT + type;
        File fileUpload = new File(directory,newFileName);
        file.transferTo(fileUpload);
        String url = "http://localhost:8090/file/download/" + newFileName;
        SysFile sysFile = new SysFile();
        sysFile.setSize(size / 1024);// 转为kb
        sysFile.setName(fileName);
        sysFile.setType(type);
        sysFile.setUrl(url);
        if (!fileService.save(sysFile)){
            throw new ServiceException(ServiceException.UN_KNOW_ERROR,"文件信息保存失败");
        }
//        返回文件下载接口地址
        return url;
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/{newFileName}")
    public void upload(@PathVariable String newFileName, HttpServletResponse response) throws IOException {
//       获取文件
        File file = new File(fileUploadPath, newFileName);
//        设置输出流格式
        try(ServletOutputStream os = response.getOutputStream()){
            response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(newFileName,"UTF-8"));
            response.setContentType("application/octet-stream");
//        读取文件字节流
            os.write(FileUtil.readBytes(file));
            os.flush();
        }catch (Exception e){
            throw new ServiceException(ServiceException.UN_KNOW_ERROR,"未知异常-文件下载");
        }

    }
}
